﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.IoC;
using Kooboo.Web.Mvc.Paging;
using Kooboo.Globalization;
using Kooboo.Commerce.Promotions.DiscountByProduct.Models;

namespace Kooboo.Commerce.Promotions.DiscountByProduct.Controllers
{
    public class DiscountByProductController : Controller
    {

        //
        // GET: /DiscountByBrand/
        public ActionResult Index(int id)
        {
            int? selectedReduceType = null;
            int? selectedProduct = null;
            var rule = Services.Current.Find(id);
            if (rule == null)
            {
                rule = new Promotion_DiscountByProduct
                {
                    DiscountRuleId = id
                };
            }
            else
            {
                selectedReduceType = rule.ReduceType;
                selectedProduct = rule.ProductId;
            }
            if (selectedProduct.HasValue)
            {
                ViewData["SelectedProductName"] = ContextContainer.Current.Resolve<IProductRepository>().Products.Where(p => p.Id == selectedProduct.Value).First().Name;
                ViewData["SelectedProduct"] = selectedProduct.Value;
            }
            else
            {
                ViewData["SelectedProductName"] = "Not Selected".Localize();
                ViewData["SelectedProduct"] = null;
            }

            ViewData["ReduceType"] = EnumHelper.ConvertEnumToSelectListItem<ReduceType>(selectedReduceType);
            ViewData["SearchProductAction"] = Url.Action("SearchProduct");
            return View(rule);
        }

        [HttpPost]
        public ActionResult Index(Promotion_DiscountByProduct promotion, String next)
        {
            if (next == "prev")
            {
                return Json(new { Data = this.Url.Action("Edit", "PromotionRule", new { Id = promotion.DiscountRuleId }) });
            }
            else
            {
                if (promotion.ReduceType == (int)ReduceType.ByFee && promotion.ReduceValue <= 0)
                {
                    return Json(new { Error = "Please enter a valid discount fee" });
                }

                if (promotion.ReduceType == (int)ReduceType.ByPercent && (promotion.ReduceValue < 0 || promotion.ReduceValue > 1))
                {
                    return Json(new { Error = "Please enter a valid discount fee" });
                }

                if (promotion.ProductId < 1)
                {
                    return Json(new { Error = "Please choose a product" });
                }

                var item = Services.Current.DataContext.Promotion_DiscountByProducts.Where(d => d.DiscountRuleId == promotion.DiscountRuleId).FirstOrDefault();
                if (item == null)
                {
                    item = new Promotion_DiscountByProduct()
                    {
                        DiscountRuleId = promotion.DiscountRuleId
                    };
                    Services.Current.DataContext.Promotion_DiscountByProducts.InsertOnSubmit(item);
                }

                item.ProductId = promotion.ProductId;
                item.ReduceType = promotion.ReduceType;
                item.ReduceValue = promotion.ReduceValue;

                Services.Current.DataContext.SubmitChanges();
            }

            return Json(new { Data = this.Url.Action("Index", "PromotionRule") });
        }

        public ActionResult SearchProduct(Int32? page)
        {
            int selectedProduct = 0;
            Int32.TryParse(Request["ProductId"], out selectedProduct);

            var productContext = ContextContainer.Current.Resolve<IProductRepository>();
            var product = productContext.Products.ToPagedList(page ?? 1, Configuration.PageSize);
            return Json(new
            {
                Items = product.Select(b => new { b.Id, b.Name, Selected = (selectedProduct > 0) ? selectedProduct == b.Id : false }).ToArray(),
                Total = product.TotalItemCount,
                PageCount = product.TotalPageCount,
                PageSize = product.PageSize,
                PageIndex = product.CurrentPageIndex
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
